package com.ruoyi.framework.interceptor;


import com.ruoyi.common.utils.UserTokenManager;
import com.ruoyi.common.utils.sign.Sign;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class AuthorizeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        MpAuthorize authorize = handlerMethod.getMethod().getAnnotation(MpAuthorize.class);
        if (authorize == null) {
            return true; // no need to authorize
        }

//        String[] allowedHeaders = authorize.value();
        // 获取请求头信息authorization信息
        String authzHeader = request.getHeader("Authorization");

        // 无token
        if (!StringUtils.hasLength(authzHeader)) {
            throw new RuntimeException("token is empty");
        }

        // 用户不存在或失效
        Map<String,Object> result = UserTokenManager.getUserId(authzHeader);
        Integer userId = Integer.valueOf(String.valueOf(result.get(Sign.CLAIM_USER_ID)));
        if (userId == null) throw  new RuntimeException("用户不存在!");
        return true;
    }
}
